package com.woniu.gateway.filter;

import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.woniu.common.constant.FinanceConstant.JWT.TOKEN_HEADER;
import static com.woniu.common.constant.FinanceConstant.WhiteListRedis.WHITE_LIST_KEY;

/**
 * packageName com.woniu.gateway.filter
 *
 * @author zxyang3636
 * @version JDK 8
 * @className LoginFilter
 * @date 2024/7/21
 * @description TODO
 */
@Order(1) // 值小，权重高，越先执行(负数也行，一般不写负数)
@Component
@Slf4j
public class LoginFilter implements GlobalFilter {
    @Autowired
    private ReactiveStringRedisTemplate redisTemplate;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getPath().toString();
        return redisTemplate.opsForHash().hasKey(WHITE_LIST_KEY, path).flatMap(b -> {
            if (b) {
                return chain.filter(exchange);
            }
            String token = request.getHeaders().getFirst("token");
            if (StringUtils.isEmpty(token)) {
                return getMono(exchange);
            }
            boolean verify = false;
            try {
                verify = JWTUtil.verify(token, TOKEN_HEADER.getBytes());
            } catch (Exception e) {
                log.error("token检查失败,e:{}", e);
                verify = false;
            }
            if (!verify) {
                return getMono(exchange);
            }
            // 放行
            return chain.filter(exchange);
        });
    }

    /**
     * @param exchange: [exchange]
     * @description 返回错误信息
     */
    private static Mono<Void> getMono(ServerWebExchange exchange) {
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        return exchange.getResponse().setComplete();
    }

}
